<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="550px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #menu="{ model, field }">
        <BasicTree
          v-model:value="model[field]"
          :treeData="treeData"
          :fieldNames="{ title: 'menuName', key: 'menuId' }"
          checkable
          selectable
          toolbar
          title="菜单分配"
          defaultExpandAll
          @check="handleCheck"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { message } from "ant-design-vue";
  import { BasicDrawer, useDrawerInner, BasicForm, useForm, BasicTree } from '@gui-pkg/antdcomponents';
  import { formSchema } from './role.data';
  import { getRoleDetail, addRole, editRole } from '@/api/system/role';
  import {  getMenuList} from '@/api/system/menu';

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const treeData = ref<TreeItem[]>([]);
  const roleId = ref('');
  const parentIds = ref([]);

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    console.log('detail---------',data)
    // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
    if (unref(treeData).length === 0) {
      treeData.value = (await getMenuList( )) as any as TreeItem[];
    }
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      roleId.value = data.record.roleId;
      const res = await getRoleDetail(data.record.roleId);
      console.log('res------------',res)
      setFieldsValue({
        ...res,
        menuIds: res.menuIds,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      // TODO custom api
      // 向后台提交菜单数据
      if (unref(isUpdate)) {
        await editRole({...values, roleId: unref(roleId), parentMenuIds: unref(parentIds)});
        message.success('编辑成功');
      } else {
        await addRole({...values, parentMenuIds: unref(parentIds)});
        message.success('新增成功');
      }
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  // 数选中的节点以及半选中的父节点
  const handleCheck = (selectedKeys, info) => {
    parentIds.value = info.halfCheckedKeys;
  }
</script>

<style lang="less" rel="stylesheet/less" scoped>
  h3.menuTitle {
    font-size: 16px;
    padding-bottom: 6px;
    margin-bottom: 6px;
    border-bottom: 1px solid #d9d9d9;
  }
</style>
